﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Singer.Shared;
using Singer.UnitTestWeb.Domain.Tests;
using Singer.UnitTestWeb.Domain.Users;
using Singer.UnitTestWeb.Infrastructure.EFCore;
using Singer.UnitTestWeb.Models.Dtos;
using System.ComponentModel.DataAnnotations;

namespace Singer.UnitTestWeb.Controllers
{
    [AllowAnonymous]
    public class EFCoreController : ApiControllerBase
    {
        TestEFCoreDbContext _dbContext;
        IMapper _mapper;
        IUserEFRepository _userEFRepository;
        public EFCoreController(
            IServiceProvider serviceProvider, 
            IUserEFRepository userEFRepository,
            IMapper mapper) : base(serviceProvider)
        {
            _userEFRepository = userEFRepository;
            _dbContext = userEFRepository.DbContext;
            _mapper = mapper;
        }

        [HttpGet]
        public async Task<List<UserDto>> GetUserListAsync()
        {
            var users = await _userEFRepository.ListAsync();
            var list = _mapper.Map<List<UserDto>>(users);
            return list;
        }

        [HttpPost]
        public async Task AddUserAsync([FromBody] UserDto dto)
        {
            User user = new User(dto.Account, dto.Name, dto.Age, dto.Password);
            //_dbContext.Users.Add(user);
            //await _dbContext.SaveChangesAsync();
            await _userEFRepository.AddAsync(user);
        }

        [HttpPost]
        public async Task EditUserAsync([FromBody] UserDto dto)
        {
            //User user = await _dbContext.Users.FirstAsync(x => x.Id == dto.Id);
            User? user = await _userEFRepository.GetAsync(x => x.Id == dto.Id);
            if (user == null)
                throw new CoreException("用户不存在");
            user.Name = dto.Name;
            user.Age = dto.Age;
            user.Password = dto.Password;
            user.Account = dto.Account;
            //await _dbContext.SaveChangesAsync();
            await _userEFRepository.UpdateAsync(user);
        }

        [HttpGet]
        public async Task DeleteUserAsync([Required]long? id)
        {
            //User? user = await _dbContext.Users.FindAsync(id);
            User? user = await _userEFRepository.GetAsync(x => x.Id == id.GetValueOrDefault(0));
            if (user == null)
                throw new CoreException("用户不存在");
            //_dbContext.Users.Remove(user);
            //await _dbContext.SaveChangesAsync();
            await _userEFRepository.DeleteAsync(user);
        }

        [HttpGet]
        public async Task<List<Test>> GetTestsAsync()
        {
            var tests = await _dbContext.Tests.ToListAsync();
            return tests;
        }
    }
}
